﻿using aier.business.logic;
using aier.dataaccess.dapper;
using aier.dataaccess.model;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace aier.wx.api.selfhost.Controllers
{
	/// <summary>
	/// 患者转诊接口
	/// </summary>
	[RoutePrefix("api/Patient")]
	public class PatientController : ApiController
	{
		public UserBll userBll { get; set; }

		public LeadBll leadBll { get; set; }

		public ILog log { get; set; }

		/// <summary>
		/// 批量新增潜在客户信息
		/// </summary>
		/// <param name="leadDtos"></param>
		/// <returns></returns>
		public IHttpActionResult BatchCreateLeadInfo(LeadDto[] leadDtos)
		{
			if (ModelState.IsValid)
			{
				try
				{
					var leadDtoOwnerGroup = leadDtos.GroupBy(t => t.ownerid)
												 .ToDictionary(t => t.Key, t => t.ToList());
					Guid[] leadids = new Guid[leadDtos.Length];
					foreach (string ownerIdName in leadDtoOwnerGroup.Keys)
					{
						var sysUser = userBll.QuerySystemUserByDomainName(ownerIdName);
						if (sysUser != null 
							&& sysUser.SystemUserId!= Guid.Empty)
						{
							var leadGroupDtos = leadDtoOwnerGroup[ownerIdName].ToArray();
							leadids = leadBll.BatchCreateLead(leadGroupDtos, sysUser.SystemUserId);
						}
					}
					return Ok(leadids);
				}
				catch (Exception ex)
				{
					log.Error(ex.Message, ex);
					return new ApiErrorResult(ex.Message, Request);
				}
			}
			else
			{
				var resp = Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
				return new ApiFailResult(resp);
			}

		}

		/// <summary>
		/// 创建患者和转诊记录
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		[ActionName(nameof(CreatePatient))]
		public IHttpActionResult CreatePatient(ReferralPatientDto referralPatientDto)
		{
			if (ModelState.IsValid)
			{
				try
				{
					var receiveUser = userBll.QuerySystemUserByDomainName(referralPatientDto.owneridname);
					if (receiveUser == null)
					{
						var resp = Request.CreateResponse(HttpStatusCode.BadRequest, "接诊人为空或在CRM找不到用户");
						return new ApiFailResult(resp);
					}
					else
					{
						var leadid = leadBll.CreatePatient(referralPatientDto, receiveUser.SystemUserId);
						var referralid = leadBll.CreateReferralPatient(referralPatientDto, receiveUser, leadid);
						return Ok(new
						{
							leadid = leadid,
							referralid = referralid
						});
					}
				}
				catch (Exception ex)
				{
					log.Error(ex.Message, ex);
					return new ApiErrorResult(ex.Message, Request);
				}

			}
			else
			{
				var resp = Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
				return new ApiFailResult(resp);
			}
		}

		/// <summary>
		/// 查询转诊患者
		/// </summary>
		/// <param name="modifiedOn">修改时间</param>
		/// <param name="pageNum">页码</param>
		/// <param name="pageSize">每页大小</param>
		/// <returns></returns>
		[HttpGet]
		[ActionName(nameof(GetPatientPageByModified))]
		public IHttpActionResult GetPatientPageByModified(DateTime? modifiedOn, int pageNum, int pageSize)
		{
			try
			{
				if (modifiedOn.HasValue && pageNum > 0)
				{
					var pageData = leadBll.QueryPatientLeadPageByModifiedOn(modifiedOn.Value, pageNum, pageSize);
					return Ok(pageData);
				}
				else
				{
					StringBuilder errorMsg = new StringBuilder();
					if (!modifiedOn.HasValue)
					{
						errorMsg.AppendLine($"{nameof(modifiedOn)}-为空或格式有误");
					}

					if (!(pageNum > 0))
					{
						errorMsg.AppendLine($"{nameof(pageNum)}-页码从1开始");
					}

					var resp = Request.CreateResponse(HttpStatusCode.BadRequest, errorMsg.ToString());
					return new ApiFailResult(resp);
				}

			}
			catch (Exception ex)
			{
				log.Error(ex.Message, ex);
				return new ApiErrorResult(ex.Message, Request);
			}
		}



		/// <summary>
		/// 查询患者转诊关系
		/// </summary>
		/// <param name="modifiedOn">修改时间</param>
		/// <param name="pageNum">页码</param>
		/// <param name="pageSize">每页大小</param>
		/// <returns></returns>
		[HttpGet]
		[ActionName(nameof(GetReferralShipPageByModified))]
		public IHttpActionResult GetReferralShipPageByModified(DateTime? modifiedOn, int pageNum, int pageSize)
		{
			try
			{
				if (modifiedOn.HasValue && pageNum > 0)
				{
					var pageData = leadBll.QueryReferralShipPageByModifiedOn(modifiedOn.Value, pageNum, pageSize);
					return Ok(pageData);
				}
				else
				{
					StringBuilder errorMsg = new StringBuilder();
					if (!modifiedOn.HasValue)
					{
						errorMsg.AppendLine($"{nameof(modifiedOn)}-为空或格式有误");
					}

					if (!(pageNum > 0))
					{
						errorMsg.AppendLine($"{nameof(pageNum)}-页码从1开始");
					}

					var resp = Request.CreateResponse(HttpStatusCode.BadRequest, errorMsg.ToString());
					return new ApiFailResult(resp);
				}

			}
			catch (Exception ex)
			{
				log.Error(ex.Message, ex);
				return new ApiErrorResult(ex.Message, Request);
			}
		}
	}
}
